﻿using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq;
using System;

namespace Bango.WindowsPhone8.SDK
{
	internal class BangoViewModel : INotifyPropertyChanged
	{
		#region Variables and Properties

		private static BangoDataContext bangoDB = new BangoDataContext();

		internal BangoViewModel()
		{
			LoadDatabase();
		}

		private void LoadDatabase()
		{
			if (bangoDB == null)
			{
				bangoDB = new BangoDataContext();
			}
		}

		internal List<StoredProfile> StoredProfiles(System.String applicationId)
		{
			List<StoredProfile> returnProfiles = new List<StoredProfile>();

			foreach (StoredProfile profile in  bangoDB.Profiles.ToList())
			{
				if (profile.ApplicationId == applicationId)
					returnProfiles.Add(profile);
			}

			return returnProfiles;
		}

		internal void SaveChanges()
		{
			try
			{
				bangoDB.SubmitChanges();
			}
			catch (System.Exception ex)
			{
				System.Console.WriteLine(ex.Message);
			}
		}

		#endregion       

		internal int SaveProfile(BangoProfile bangoProfile)
		{
			StoredProfile sProfile = new StoredProfile(bangoProfile);
			bangoDB.Profiles.InsertOnSubmit(sProfile);
			SaveChanges();
			return sProfile.ProfileId;
		}

		internal bool DeleteProfile(StoredProfile storedProfile)
		{
			bool returnValue = false;
			try
			{
				if (storedProfile != null)
				{
					foreach (StoredEvent evnt in storedProfile.Events)
					{
						bangoDB.EventParameters.DeleteAllOnSubmit(evnt.EventParameters);
					}
					bangoDB.Events.DeleteAllOnSubmit(storedProfile.Events);
				   
					bangoDB.Profiles.DeleteOnSubmit(storedProfile);

					SaveChanges();
					returnValue = true;
				}
			}
			catch (Exception ex)
			{
				System.Console.WriteLine(ex.Message);
				returnValue = false;
			}

			return returnValue;
		}

		internal static void UpdatePostedProfile(StoredProfile storedProfile)
		{
			try
			{
				foreach (StoredEvent evnt in storedProfile.Events)
				{
					bangoDB.EventParameters.AttachAll(evnt.EventParameters, true);
				}
				bangoDB.Profiles.Attach(storedProfile, true);
				bangoDB.Events.AttachAll(storedProfile.Events, true);           
			}
			catch (System.Exception ex)
			{
				Console.WriteLine(ex.Message);
			}
		}

		#region INotifyPropertyChanged Members

		public event PropertyChangedEventHandler PropertyChanged;

		public void NotifyPropertyChanged(string propertyName)
		{
			if (PropertyChanged != null)
			{
				PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
			}
		}
		#endregion
	}
}
